<template>
	<view class="order-container">
		<!-- 订单状态头部 -->
		<view class="order-status-header">
			<text class="status-text">{{ statusText }}</text>
			<image class="status-icon" :src="statusIcon" mode="aspectFit"></image>
		</view>

		<!-- 收货地址信息 -->
		<view class="address-info" v-if="orderInfo.address_info">
			<view class="address-icon">
				<image src="/static/images/location.png" mode="aspectFit"></image>
			</view>
			<view class="address-content">
				<view class="user-info">
					<text class="name">{{ orderInfo.address_info?.name || '暂无' }}</text>
					<text class="phone">{{ orderInfo.address_info?.tel || '暂无' }}</text>
				</view>
				<view class="address-detail">
					{{ orderInfo.address_info?.province || '' }}
					{{ orderInfo.address_info?.city ? '- ' + orderInfo.address_info.city : '' }}
					{{ orderInfo.address_info?.country ? '- ' + orderInfo.address_info.country : '' }}
					{{ orderInfo.address_info?.addressDetail ? '- ' + orderInfo.address_info.addressDetail : '' }}
				</view>
			</view>
		</view>

		<!-- 商品信息 -->
		<view class="goods-info" v-if="goodsInfo && goodsInfo.length > 0">
			<view class="goods-item" v-for="item in goodsInfo" :key="item.id">
				<image class="goods-image" :src="item.thumb_path || '/static/images/empty-image-error.png'"
					mode="aspectFill"></image>
				<view class="goods-detail">
					<text class="goods-name text-ellipsis">{{ item.title || '加载中...' }}</text>
					<view class="price-wrap">
						<text class="goods-price">¥{{ item.sell_price || '0' }}</text>
						<text class="goods-count">x{{ item.number || 1 }}</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 订单信息 -->
		<view class="order-info">
			<view class="info-item">
				<text class="label">下单时间</text>
				<text class="value">{{ formatDate(orderInfo.add_time) }}</text>
			</view>
			<view class="info-item">
				<text class="label">商品总价</text>
				<text class="value">¥{{ orderInfo.total_price }}</text>
			</view>
			<view class="info-item">
				<text class="label">商品数量</text>
				<text class="value">{{ orderInfo.number }}</text>
			</view>

			<view class="info-item" v-if="orderInfo.actual_price">
				<text class="label">实际付款</text>
				<text class="value">{{ orderInfo.actual_price }}</text>
			</view>
			<view class="info-item" v-if="orderInfo.success_time">
				<text class="label">实际下单时间</text>
				<text class="value">{{ dateformat(orderInfo.success_time) }}</text>
			</view>

			<view class="info-item">
				<text class="label">付款方式</text>
				<text class="value">微信支付</text>
			</view>
			<view class="info-item">
				<text class="label">运费险</text>
				<text class="value">¥0.00</text>
			</view>
			<view class="info-item">
				<text class="label">订单号</text>
				<text class="value copy-text" @tap="copyOrderNo">{{ orderInfo.order_id }} 复制</text>
			</view>
			<view class="info-item">
				<text class="label">联系客服</text>
				<text class="value service-btn" @tap="contactService">联系客服</text>
			</view>
		</view>

		<!-- 二维码弹窗 -->
		<view class="qrcode-popup" v-if="isShowQrcode">
			<view class="qrcode-content">
				<view class="qrcode-title">扫码付款</view>
				<view class="qrcode-box">
					<image :src="img_url" mode="aspectFit"></image>
				</view>
				<view class="qrcode-footer">
					<button class="confirm-btn" @tap="endCheckStatus">取消付款</button>
				</view>
			</view>
		</view>

		<!-- 底部按钮 -->
		<view class="bottom-actions" v-if="orderInfo.is_cancel === 0 && orderInfo.status === 0">
			<button class="action-btn cancel" @tap="cancelOrder">取消订单</button>
			<button class="action-btn pay" @tap="payOrder">立即付款</button>
		</view>
		<view class="bottom-actions" v-if="orderInfo.is_cancel === 1">
			<button class="action-btn delete" @tap="deleteOrder">删除订单</button>
			<button class="action-btn cancelled" disabled>订单已取消</button>
		</view>
		<!-- 查询物流 -->
		<view class="bottom-actions" v-if="orderInfo.status === 1">
			<button class="action-btn query" @tap="queryLogistics">查询物流</button>
		</view>

	</view>
</template>

<script setup>
import { ref, computed } from 'vue';
import { onLoad, onShow, onHide, onUnload } from '@dcloudio/uni-app';
import { reqOrderInfo, reqCancelOrder, reqDelOrder, reqWxPay, reqQueryPayOrder } from '@/api/order';
import { reqCarGoods } from '@/api/user';
import moment from 'moment';
import QRCode from 'qrcode';
// 设置中文语言
moment.locale('zh-cn');

const isPaying = ref(false);//是否正在支付
const order_id = ref('');
const isShowQrcode = ref(false);//是否显示二维码
const checkStatusTimer = ref(null);//心跳检测定时器
const img_url = ref('');//二维码图片
// 订单信息
const orderInfo = ref({
	address_info: {
		name: '',
		tel: '',
		province: '',
		city: '',
		country: '',
		addressDetail: ''
	},
	goods_ids: '',
	order_id: '',
	add_time: '',
	total_price: 0,
	number: 0,
});
// 商品信息
const goodsInfo = ref([]);

onLoad((options) => {
	if (options.order_id) {
		order_id.value = options.order_id;
		console.log(order_id.value);
		OrderInfo();
	}

});
//切换后台时，结束心跳检测
onHide(() => {
	console.log('切换后台，结束心跳检测')
	endCheckStatus()
})
//切换前台时，开始心跳检测
onShow(() => {
	console.log('切换前台，开始心跳检测')
	CheckOrderStatus()
})
//卸载时，结束心跳检测
onUnload(() => {
	console.log('卸载，结束心跳检测')
	endCheckStatus()
})
//通过订单信息获取商品id订单信息
const getGoodsInfo = async () => {
	try {
		uni.showLoading({
			title: '加载中...',
			mask: true
		});
		const res = await reqCarGoods(orderInfo.value.goods_ids);
		uni.hideLoading();
		if (res.message) {
			goodsInfo.value = res.message;
			console.log(goodsInfo.value);
		}
	} catch (error) {
		uni.hideLoading();
		uni.showToast({
			title: '获取商品信息失败',
			icon: 'none'
		});
	}
}
// 获取订单信息
const OrderInfo = async () => {
	try {
		uni.showLoading({
			title: '加载中...',
			mask: true
		});
		const res = await reqOrderInfo(order_id.value);
		uni.hideLoading();
		if (res && res.address_info) {
			orderInfo.value = {
				...res,
				address_info: {
					name: res.address_info.name || '',
					tel: res.address_info.tel || '',
					province: res.address_info.province || '',
					city: res.address_info.city || '',
					country: res.address_info.country || '',
					addressDetail: res.address_info.addressDetail || ''

				}
			};
		}
		if (res.goods_ids) {
			await getGoodsInfo();
		}
	} catch (error) {
		uni.hideLoading();
		uni.showToast({
			title: '获取订单信息失败',
			icon: 'none'
		});
		console.error('获取订单信息错误：', error);
	}
}

// 格式化日期
const formatDate = (timestamp) => {
	return moment(timestamp * 1000).format('YYYY-MM-DD HH:mm:ss');
};
const dateformat = (date, format = 'YYYY-MM-DD HH:mm:ss') => {
	return moment(date).format(format)
}

// 复制订单号
const copyOrderNo = () => {
	uni.setClipboardData({
		data: orderInfo.value.order_id,
		success: () => {
			uni.showToast({
				title: '复制成功',
				icon: 'success'
			});
		}
	});
};

// 联系客服
const contactService = () => {
	// TODO: 实现联系客服功能
};

// 取消订单
const cancelOrder = async () => {
	uni.showModal({
		title: '提示',
		content: '确定要取消订单吗？',
		success: async (res) => {
			if (res.confirm) {
				try {
					uni.showLoading({
						title: '取消中...',
						mask: true
					});
					const result = await reqCancelOrder(order_id.value);
					uni.hideLoading();
					if (result) {
						uni.showToast({
							title: '订单已取消',
							icon: 'success'
						});
						//要将is_cancel设置为1
						orderInfo.value.is_cancel = 1;
						console.log(orderInfo.value);
						// 重新获取订单信息
						await OrderInfo();
					}
				} catch (error) {
					uni.hideLoading();
					uni.showToast({
						title: '取消订单失败',
						icon: 'none'
					});
				}
			}
		}
	});
};

// 支付订单
const payOrder = async () => {
	// #ifdef MP-WEIXIN
	//获取openid
	const openid = uni.getStorageSync('openid');
	console.log('openid=>', openid)
	//获取订单id
	const order_id = orderInfo.value.order_id;
	console.log('order_id=>', order_id)
	//获取订单总价
	const total_price = orderInfo.value.total_price;
	console.log('total_price=>', total_price)
	//调用支付接口
	const wxPayResult = await reqWxPay({ order_id, total_price, openid });
	console.log('payResult=>', wxPayResult)
	const { status: wxStatus, data: wxData } = wxPayResult;
	if (wxStatus === 400) {
		uni.showToast({
			title: '订单重复',
			icon: 'none'
		});
		return;
	}
	// 将接口返回的预支付相关参数，传递给wx.requestPayment支付api,从而拉取支付
	uni.requestPayment({
		...wxData,
		success: async () => {
			console.log('支付成功')
			await OrderInfo()
			await getGoodsInfo()
		},
		fail: () => {
			uni.showToast({
				title: '支付失败',
				icon: 'none'
			});
			//关闭心跳检测	
			endCheckStatus()
		}
	})

	// 设置心跳检测
	console.log('准备开始心跳检测')
	if (checkStatusTimer.value) {
		clearInterval(checkStatusTimer.value);
	}
	checkStatusTimer.value = setInterval(() => {
		console.log('进入心跳检测, 当前时间:', new Date().toLocaleString())
		CheckOrderStatus()
	}, 2000)
	console.log('心跳检测定时器已设置')
	// #endif

	//H5支付
	// #ifdef H5
	// 用户点击付款按钮，调用支付接口
	isPaying.value = true;
	console.log('orderInfo=>', orderInfo.value)

	//调用支付接口
	// 1. 调用支付接口
	let orderData = {
		order_id: orderInfo.value.order_id,
		total_price: orderInfo.value.total_price,
	}
	console.log('orderData=>', orderData)

	// 2. 调用支付接口
	const { status, data } = await reqWxPay(orderData);
	if (status === 200) {
		console.log('开始生成二维码')
		img_url.value = await QRCode.toDataURL(data.code_url);
		console.log('img_url=>', img_url.value)
		isShowQrcode.value = true;
		//4.心跳检测，查询支付状态
		console.log('准备开始心跳检测')
		if (checkStatusTimer.value) {
			clearInterval(checkStatusTimer.value);
		}
		checkStatusTimer.value = setInterval(() => {
			console.log('进入心跳检测, 当前时间:', new Date().toLocaleString())
			CheckOrderStatus()
		}, 2000)
		console.log('心跳检测定时器已设置')
	} else {
		//关闭心跳检测
		endCheckStatus()
		uni.showToast({
			title: '订单重复',
			icon: 'none'
		});
	}
	// #endif
};

// 查询支付状态
const CheckOrderStatus = async () => {
	try {
		console.log('开始查询订单状态, order_id=>', order_id.value)
		const { code } = await reqQueryPayOrder(order_id.value);
		console.log('查询支付状态返回 code=>', code)
		if (code === 20000) {
			console.log('支付成功，准备结束心跳检测')
			endCheckStatus()
			uni.showToast({
				title: '支付成功',
				icon: 'success'
			});
			//最新获取订单信息，并更新订单状态
			await OrderInfo();
			await getGoodsInfo();
			// 支付成功，将订单状态设置为已支付
			orderInfo.value.status = 1;
			console.log('支付成功，订单状态已更新为已支付')
			console.log('orderInfo=>', orderInfo.value)
		}
	} catch (error) {
		console.error('查询支付状态出错:', error)
	}
}

// 结束心跳检测，点击确定按钮后，结束心跳检测，并关闭二维码弹窗
const endCheckStatus = async () => {
	console.log('结束心跳检测')
	if (checkStatusTimer.value) {
		clearInterval(checkStatusTimer.value);
		checkStatusTimer.value = null;
		//最新获取订单信息，并更新订单状态
		await OrderInfo();
		await getGoodsInfo();
	}
	isShowQrcode.value = false;
}

// 删除订单
const deleteOrder = async () => {
	uni.showModal({
		title: '提示',
		content: '确定要删除订单吗？',
		success: async (res) => {
			if (res.confirm) {
				try {
					uni.showLoading({
						title: '删除中...',
						mask: true
					});
					const result = await reqDelOrder(order_id.value);
					uni.hideLoading();
					if (result) {
						uni.showToast({
							title: '订单已删除',
							icon: 'success'
						});
						//返回上一页
						uni.navigateBack();
					}
				} catch (error) {
					uni.hideLoading();
					uni.showToast({
						title: '删除订单失败',
						icon: 'none'
					});
				}
			}
		}
	});
};

// 订单状态文本
const statusText = computed(() => {
	if (orderInfo.value.is_cancel === 1) return '已取消';
	return orderInfo.value.status === 1 ? '已付款' : '待付款';
});

// 订单状态图标
const statusIcon = computed(() => {
	if (orderInfo.value.is_cancel === 1) return '/static/images/取消订单.png';
	return orderInfo.value.status === 1 ? '/static/images/已付款.png' : '/static/images/wait-payment.png';
});
</script>

<style lang="scss" scoped>
@import '@/uni.scss';

.order-container {
	min-height: 100vh;
	background-color: #f7f7f7;
	padding-bottom: 120rpx;

	.order-status-header {
		height: 200rpx;
		background-color: #ff6b01;
		color: #fff;
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 0 40rpx;
		transition: background-color 0.3s ease;

		.status-text {
			font-size: 36rpx;
			font-weight: 500;
		}

		.status-icon {
			width: 120rpx;
			height: 120rpx;
			transition: opacity 0.3s ease;
		}
	}

	.address-info {
		background-color: #fff;
		margin: 20rpx;
		padding: 30rpx;
		border-radius: 12rpx;
		display: flex;
		align-items: flex-start;

		.address-icon {
			margin-right: 20rpx;

			image {
				width: 40rpx;
				height: 40rpx;
			}
		}

		.address-content {
			flex: 1;

			.user-info {
				margin-bottom: 10rpx;

				.name {
					font-size: 32rpx;
					font-weight: 500;
					margin-right: 20rpx;
				}

				.phone {
					font-size: 28rpx;
					color: #666;
				}
			}

			.address-detail {
				font-size: 28rpx;
				color: #333;
				line-height: 1.4;
			}
		}
	}

	.goods-info {
		background-color: #fff;
		margin: 20rpx;
		padding: 30rpx;
		border-radius: 12rpx;

		.goods-item {
			display: flex;
			align-items: flex-start;
			padding: 20rpx 0;

			.goods-image {
				width: 180rpx;
				height: 180rpx;
				border-radius: 8rpx;
				margin-right: 24rpx;
				background-color: #f8f8f8;
			}

			.goods-detail {
				flex: 1;
				display: flex;
				flex-direction: column;
				justify-content: space-between;
				min-height: 180rpx;
				padding: 10rpx 0;

				.goods-name {
					font-size: 28rpx;
					color: #333;
					line-height: 1.5;
					margin-bottom: 20rpx;
					font-weight: 500;
				}

				.text-ellipsis {
					overflow: hidden;
					text-overflow: ellipsis;
					display: -webkit-box;
					-webkit-box-orient: vertical;
					-webkit-line-clamp: 2;
				}

				.price-wrap {
					display: flex;
					justify-content: space-between;
					align-items: center;

					.goods-price {
						font-size: 36rpx;
						color: #ff6b01;
						font-weight: bold;
					}

					.goods-count {
						font-size: 26rpx;
						color: #999;
					}
				}
			}
		}
	}

	.order-info {
		background-color: #fff;
		margin: 20rpx;
		padding: 30rpx;
		border-radius: 12rpx;

		.info-item {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 20rpx;
			font-size: 28rpx;

			&:last-child {
				margin-bottom: 0;
			}

			.label {
				color: #666;
			}

			.value {
				color: #333;

				&.copy-text {
					color: #576B95;
				}

				&.service-btn {
					color: #576B95;
				}
			}
		}
	}

	.qrcode-container {
		position: fixed;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		background: #fff;
		padding: 30rpx;
		border-radius: 12rpx;
		box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
		z-index: 999;

		image {
			width: 400rpx;
			height: 400rpx;
			display: block;
		}

		&::after {
			content: '请使用微信扫码支付';
			display: block;
			text-align: center;
			font-size: 28rpx;
			color: #666;
			margin-top: 20rpx;
		}
	}

	.qrcode-popup {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: rgba(0, 0, 0, 0.6);
		z-index: 999;
		display: flex;
		align-items: center;
		justify-content: center;

		.qrcode-content {
			width: 600rpx;
			background: #fff;
			border-radius: 20rpx;
			overflow: hidden;

			.qrcode-title {
				font-size: 32rpx;
				color: #333;
				text-align: center;
				padding: 30rpx 0;
				border-bottom: 1rpx solid #eee;
			}

			.qrcode-box {
				padding: 40rpx;
				display: flex;
				justify-content: center;

				image {
					width: 400rpx;
					height: 400rpx;
				}
			}

			.qrcode-footer {
				padding: 20rpx 40rpx 40rpx;

				.confirm-btn {
					width: 100%;
					height: 80rpx;
					line-height: 80rpx;
					text-align: center;
					background: #ff6b01;
					color: #fff;
					font-size: 30rpx;
					border-radius: 40rpx;
					border: none;

					&:active {
						opacity: 0.9;
					}
				}
			}
		}
	}

	.bottom-actions {
		position: fixed;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: #fff;
		padding: 20rpx;
		display: flex;
		justify-content: flex-end;
		box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);

		.action-btn {
			margin-left: 20rpx;
			width: 180rpx;
			height: 80rpx;
			line-height: 80rpx;
			text-align: center;
			border-radius: 40rpx;
			font-size: 28rpx;

			&.cancel {
				color: #666;
				background-color: #f5f5f5;
				border: none;
			}

			&.pay {
				color: #fff;
				background-color: #ff6b01;
				border: none;
			}

			&.cancelled {
				color: #999;
				background-color: #f5f5f5;
				border: none;
			}

			&.delete {
				color: #fff;
				background-color: #ff4d4f;
				border: none;
			}

			&.query {
				color: #fff;
				background-color: #4921d9;
				border: none;
			}
		}
	}
}
</style>
